package com.skyline.user.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.skyline.base.service.impl.BaseServiceImpl;
import com.skyline.base.type.Activity;
import com.skyline.base.type.Authority;
import com.skyline.user.dao.BasicUserDao;
import com.skyline.user.model.User;
import com.skyline.user.service.BasicUserService;
import com.skyline.wo.dao.AlbumDao;
import com.skyline.wo.service.CategoryService;

//TODO:加注释
@Service("basicUserService")
public class BasicUserServiceImpl extends BaseServiceImpl implements BasicUserService {
	@Autowired
	private BasicUserDao basicUserDao;
	@Autowired
	private AlbumDao albumDao;

	@Autowired
	private CategoryService categoryService;

	@Value("${album.cover.defaultCover}")
	private String cover;
	@Value("${album.cover.defaultExt}")
	private String ext;

	public void regist(String email, String password, String ip) {
		password = encodePassword(password);
		basicUserDao.insertUser(email, password, ip);
		User user = basicUserDao.queryUserByEmail(email);
		Long userId = user.getId();
		String nickname = user.getNickname();
		String portrait = user.getPortrait();
		albumDao.insertAlbumReturnId(userId, nickname, portrait, "头像相册", "", "", Authority.PUBLIC,
				Activity.UNDELETABLE, cover, ext);
		categoryService.createDefaultCategory(userId, portrait, nickname);
	}

	public User login(String email, String password, String loginIP) {
		password = encodePassword(password);
		User user = basicUserDao.queryUserByEmailAndPassword(email, password);
		if (user != null) {
			basicUserDao.updateLoginInfo(user.getId(), loginIP);
		}
		return user;
	}

	public boolean isUserExist(String email) {
		int count = basicUserDao.countUserByEmail(email);
		if (count == 0) {
			return false;
		} else {
			return true;
		}
	}

	private String encodePassword(String password) {
		return String.valueOf(DigestUtils.md5Hex(password));
	}
}
